/**
 * iframe tab打开回收内存
 */
$.fn.panel.defaults.onBeforeDestroy = function() {
	var frame = $('iframe', this);
	try {
		if (frame.length > 0) {
			for ( var i = 0; i < frame.length; i++) {
				frame[i].contentWindow.document.write('');
				frame[i].contentWindow.close();
			}
			frame.remove();
			if ($.browser.msie) {
				CollectGarbage();
			}
		}
	} catch (e) {
	}
};
/**
 * 扩张平滑数据结构
 */
$.fn.tree.defaults.loadFilter = function(data, parent) {
	var opt = $(this).data().tree.options;
	var idFiled, textFiled, parentField;
	if (opt.parentField) {
		idFiled = opt.idFiled || 'id';
		textFiled = opt.textFiled || 'text';
		parentField = opt.parentField;
		var i, l, treeData = [], tmpMap = [];
		for (i = 0, l = data.length; i < l; i++) {
			tmpMap[data[i][idFiled]] = data[i];
		}
		for (i = 0, l = data.length; i < l; i++) {
			if (tmpMap[data[i][parentField]] && data[i][idFiled] != data[i][parentField]) {
				if (!tmpMap[data[i][parentField]]['children'])
					tmpMap[data[i][parentField]]['children'] = [];
				data[i]['text'] = data[i][textFiled];
				tmpMap[data[i][parentField]]['children'].push(data[i]);
			} else {
				data[i]['text'] = data[i][textFiled];
				treeData.push(data[i]);
			}
		}
		return treeData;
	}
	return data;
};
/**
 * 防止easy-ui超出边界
 * @param left
 * @param top
 * @returns 
 */
var easyuiPanelOnMove = function(left, top) {
	var l = left;
	var t = top;
	if (l < 1) {
		l = 1;
	}
	if (t < 1) {
		t = 1;
	}
	var width = parseInt($(this).parent().css('width')) + 14;
	var height = parseInt($(this).parent().css('height')) + 14;
	var right = l + width;
	var buttom = t + height;
	var browserWidth = $(window).width();
	var browserHeight = $(window).height();
	if (right > browserWidth) {
		l = browserWidth - width;
	}
	if (buttom > browserHeight) {
		t = browserHeight - height;
	}
	$(this).parent().css({/* 修正面板位置 */
		left : l,
		top : t
	});
};
$.fn.dialog.defaults.onMove = easyuiPanelOnMove;
$.fn.window.defaults.onMove = easyuiPanelOnMove;
$.fn.panel.defaults.onMove = easyuiPanelOnMove;
/**
 * 修改jquery序列化格式，将form表单序列化成一个对象
 */
serializeObject = function(form) {
	var o = {};
	$.each(form.serializeArray(), function(index) {
		if (o[this['name']]) {
			o[this['name']] = o[this['name']] + "," + this['value'];
		} else {
			o[this['name']] = this['value'];
		}
	});
	return o;
};
(function($) {
	$.fn.my97 = function(options, params) {
		if (typeof options == "string") {
			return $.fn.my97.methods[options](this, params);
		}
		options = options || {};
		if (!WdatePicker) {
			alert("未引入My97js包！");
			return;
		}
		return this.each(function() {
			var data = $.data(this, "my97");
			var newOptions;
			if (data) {
				newOptions = $.extend(data.options, options);
				data.opts = newOptions;
			} else {
				newOptions = $.extend({}, $.fn.my97.defaults, $.fn.my97
						.parseOptions(this), options);
				$.data(this, "my97", {
					options : newOptions
				});
			}
			$(this).addClass('Wdate').click(function() {
				WdatePicker(newOptions);
			});
		});
	};
	$.fn.my97.methods = {
		setValue : function(target, params) {
			target.val(params);
		},
		getValue : function(target) {
			return target.val();
		},
		clearValue : function(target) {
			target.val('');
		}
	};
	$.fn.my97.parseOptions = function(target) {
		return $.extend({}, $.parser.parseOptions(target, [ "el", "vel",
				"weekMethod", "lang", "skin", "dateFmt", "realDateFmt",
				"realTimeFmt", "realFullFmt", "minDate", "maxDate",
				"startDate", {
					doubleCalendar : "boolean",
					enableKeyboard : "boolean",
					enableInputMask : "boolean",
					autoUpdateOnChanged : "boolean",
					firstDayOfWeek : "number",
					isShowWeek : "boolean",
					highLineWeekDay : "boolean",
					isShowClear : "boolean",
					isShowToday : "boolean",
					isShowOthers : "boolean",
					readOnly : "boolean",
					errDealMode : "boolean",
					autoPickDate : "boolean",
					qsEnabled : "boolean",
					autoShowQS : "boolean",
					opposite : "boolean"
				} ]));
	};
	$.fn.my97.defaults = {
		dateFmt : 'yyyy-MM-dd HH:mm:ss'
	};
	$.parser.plugins.push('my97');
	})(jQuery);
//修改jQuery的AJAX默认属性和方法
$.ajaxSetup({
	type : 'POST',
	error : function(XMLHttpRequest, textStatus, errorThrown) {
		$.messager.progress('close');
		$.messager.alert('请求返回错误', XMLHttpRequest.responseText);
	}
});
//获取当前工程目录
project_path = function() {
	var curWwwPath = window.document.location.href;
	var pathName = window.document.location.pathname;
	var pos = curWwwPath.indexOf(pathName);
	var localhostPaht = curWwwPath.substring(0, pos);
	var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
	return (localhostPaht + projectName);
};

$.fn.treegrid.defaults.loadFilter = function(data, parentId) {
	var opt = $(this).data().treegrid.options;
	var idFiled, textFiled, parentField;
	if (opt.parentField) {
		idFiled = opt.idFiled || 'id';
		textFiled = opt.textFiled || 'text';
		parentField = opt.parentField;
		var i, l, treeData = [], tmpMap = [];
		for (i = 0, l = data.length; i < l; i++) {
			tmpMap[data[i][idFiled]] = data[i];
		}
		for (i = 0, l = data.length; i < l; i++) {
			if (tmpMap[data[i][parentField]] && data[i][idFiled] != data[i][parentField]) {
				if (!tmpMap[data[i][parentField]]['children'])
					tmpMap[data[i][parentField]]['children'] = [];
				data[i]['text'] = data[i][textFiled];
				tmpMap[data[i][parentField]]['children'].push(data[i]);
			} else {
				data[i]['text'] = data[i][textFiled];
				treeData.push(data[i]);
			}
		}
		return treeData;
	}
	return data;
};

/**
 * 
 */
$.fn.combotree.defaults.loadFilter = $.fn.tree.defaults.loadFilter;

formatString = function(str) {
	for ( var i = 0; i < arguments.length - 1; i++) {
		str = str.replace("{" + i + "}", arguments[i + 1]);
	}
	return str;
}; 
var iconData = [ {
	value : '',
	text : '默认',
	label: '默认图标'
},
{
	value : 'usermgr',
	text : '用户管理(usermgr)',
	label: '用户管理类图标'
},
{
	value : 'paramter',
	text : '参数配置(paramter)',
	label: '参数配置类图标'
}
, {
	value : 'systemconfig',
	text : '系统配置(systemconfig)',
	label: '系统配置类图标'
} ];
/**
 * 修改datagrid的右键标题弹出排序
 * @param e
 * @param field
 * @returns
 */
var createGridHeaderContextMenu = function(e, field) {
    e.preventDefault();
    var grid = $(this);/* grid本身 */
    var headerContextMenu = this.headerContextMenu;/* grid上的列头菜单对象 */
    if (!headerContextMenu) {
            var tmenu = $('<div style="width:100px;"></div>').appendTo('body');
            var asc = $('<div iconCls="icon-asc" field="asc">升序</div>').appendTo(tmenu);
            var desc = $('<div iconCls="icon-desc" field="desc">降序</div>').appendTo(tmenu);
            var filedHTML = $('<div iconCls="icon-columns"></div>');
            var span = $('<span>显示列/隐藏列</span>');
            var spdiv = $('<div></div>');
            var fields = grid.datagrid('getColumnFields');
            for ( var i = 0; i < fields.length; i++) {
                    var fildOption = grid.datagrid('getColumnOption', fields[i]);
                    if (!fildOption.hidden) {
                            $('<div iconCls="icon-checked" field="' + fields[i] + '"/>').html(fildOption.title).appendTo(spdiv);
                    } else {
                            $('<div iconCls="icon-unchecked" field="' + fields[i] + '"/>').html(fildOption.title).appendTo(spdiv);
                    }
            }
            span.appendTo(filedHTML);
            spdiv.appendTo(filedHTML);
            filedHTML.appendTo(tmenu);
            headerContextMenu = this.headerContextMenu = tmenu.menu({
                    onClick : function(item) {
                            var f = $(this).attr('field')
                            var fieldProperty = $(item.target).attr('field');
                            if (item.iconCls == 'icon-checked') {
                                    grid.datagrid('hideColumn', fieldProperty);
                                    $(this).menu('setIcon', {
                                            target : item.target,
                                            iconCls : 'icon-unchecked'
                                    });
                            }
                            if (item.iconCls == 'icon-unchecked') {
                                    grid.datagrid('showColumn', fieldProperty);
                                    $(this).menu('setIcon', {
                                            target : item.target,
                                            iconCls : 'icon-checked'
                                    });
                            }
                            if (item.iconCls == 'icon-asc') {
                                    var options = grid.datagrid('options');
                                    options.sortName = f;
                                    options.sortOrder =fieldProperty;
                                    grid.datagrid('reload');
                            }
                            if (item.iconCls == 'icon-desc') {
                                    var options = grid.datagrid('options');
                                    options.sortName = f;
                                    options.sortOrder =fieldProperty;
                                    grid.datagrid('reload');
                            }
                    }
            });
    }
    headerContextMenu.attr('field',field);
    headerContextMenu.menu('show', {
            left : e.pageX,
            top : e.pageY
    });
    var fd = grid.datagrid('getColumnOption',field);
    if(!fd.sortable){
        var itemAsc = headerContextMenu.menu('findItem','升序');
        headerContextMenu.menu('disableItem',itemAsc.target);
        var itemDesc = headerContextMenu.menu('findItem','降序');
        headerContextMenu.menu('disableItem',itemDesc.target);
    }
};

//鼠标移入显示下划线	
function onMouseOverName(obj){
	$(obj).css({"textDecoration":"underline"});
}
//鼠标离开去掉下划线	
function onMouseOutName(obj){
	$(obj).css({"textDecoration":""});
}

//鼠标移入移出:改变背景色
function mouseOverOut(pageContext,image,obj){
	 var imageUrl=pageContext+'/images/'+image;
	 $("#"+obj.id).css({"background-image":"url('"+imageUrl+"')"})
}
//增加表格隔行变色效果
$.fn.zebra = function(options) {
		var settings={
				zebra: true,//是否增加隔行换色功能
		        selected:false,//是否增加选中变色功能
		        hover:false//是否增加鼠标悬停变色功能
		}
		var _opts = $.extend(settings, options);
		$tr=$(this).find("tr:visible");	
		if(_opts.zebra){
			$tr.removeClass("row-odd");
			$tr.filter(':odd').addClass("row-odd"); //隔行行变色
			$tr.filter(':even').addClass("row-even"); //隔行行变色
		}
		if(_opts.selected){
			$tr.click(function(){ //选中变色
				$(this).addClass('row-selected').siblings().removeClass('row-selected');
			});
		}
		if(_opts.hover){
			$tr.mouseover(function(){ //鼠标悬停变色			
				$(this).addClass('row-hover');
			});	
			$tr.mouseout(function(){ //鼠标悬停变色			
				$(this).removeClass('row-hover');
			});	
		}			
}
//扩展Jquery easyui验证手机号码
$.extend($.fn.validatebox.defaults.rules, { 
	  mobile : {// 验证手机号码          
		  validator : function(value) {              
			   return /^1[3|4|5|8][0-9]\d{4,8}$/i.test(value);   
	      },          
	      message : '手机号码格式不正确'     
	  },
	  bound : {// 上下限验证          
		  validator : function(value) {              
			   return /^\d*?\.?\d*?$/i.test(value);   
	      },          
	      message : '上下限必须为数值'     
	  },
	  english : {// 验证英语          
		  validator : function(value) {              
			  return /^[A-Za-z]+$/i.test(value);          
		  },          
		  message : '请输入英文'     
      },
	  chinese : {// 验证中文          
		  validator : function(value) { 
			 return /^[u4E00-u9FA5]+$/i.test(value);
		  },         
		  message : '不允许输入中文'
	  },
	lessThen:{//小于等于某个控件中数字的值，传入一个其他控件的id
		validator: function(value, param){
			var intParam=parseFloat($('#'+param).val());
			var intValue=parseFloat(value);
			return intValue<=intParam;
		},
		message:'该值必须小于等于阀值上限的值'
	},
	moreThen:{//大于等于某个控件中数字的值，传入一个其他控件的id
		validator: function(value, param){
			var intParam=parseFloat($('#'+param).val());
			var intValue=parseFloat(value);
			return intParam<=intValue;
		},
		message:'该值必须大于等于阀值下限的值'
	},
	specialCharFilter:{
		validator: function(value){
			return (/^[^\|"'<>%`~!@#$^&*()={}:;,./?！￥……（）；：，、？。‘’“”【】]*$/).test(value)
		},
		message:'不能包含特殊字符'
	},
	ipValidate:{  
        validator:function(value){  
        	var patten=new RegExp(/^((25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)\.){3}(25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)$/);
    		return patten.test(value);
        },  
        message: 'ip地址格式不正确'  
    },
    letterOnly:{  
        validator:function(value){  
        	var patten=new RegExp(/^\w+$/);
    		return patten.test(value);
        },  
        message: '只能输入数字、26个英文字母或者下划线组成的字符串'  
    },
    maxLength: {  
        validator: function(value, param){  	        	
        	var len = 0;   
            for (var i=0; i<value.length; i++) {   
                if (value.charCodeAt(i)>127 || value.charCodeAt(i)==94) {   
                    len += 2;   
                } else {   
                    len ++;   
                }   
            }   	 	        	       	
            return len <= param[0];  
        },  
        message: '最大输入字符长度为{0}，汉字占两位'  
    } 
}); 

//格式化日期 
function date2str(x,fmt)//x:Date类型的对象；fmt:日期格式，如yyyyMMddhh,yyyyMMdd,yyyyMM
{
	var z = {M:x.getMonth()+1,d:x.getDate(),h:x.getHours(),m:x.getMinutes(),s:x.getSeconds()};
	fmt = fmt.replace(/(M+|d+|h+|m+|s+)/g,function(v) {return ((v.length>1?"0":"")+eval('z.'+v.slice(-1))).slice(-2)});
	return fmt.replace(/(y+)/g,function(v) {return x.getFullYear().toString().slice(-v.length)});
}

//字符拼接
function StringBuffer(){
	this.__string__ = new Array();
}
StringBuffer.prototype.append = function(str){
	this.__string__.push(str);
	return this;
}
StringBuffer.prototype.toString = function(){
	return this.__string__.join("");
}
$.fn.datagrid.defaults.onHeaderContextMenu = createGridHeaderContextMenu;
$.fn.treegrid.defaults.onHeaderContextMenu = createGridHeaderContextMenu;